| 132 | } |
| 133 | |
| 134 | func (c *Client) AddToAllowlist(ctx context.Context, list *ent.AllowList, items []*models.AllowlistItem) (int, error) { |
| 135 | added := 0 |
| 136 | |
| 137 | c.Log.Debugf("adding %d values to allowlist %s", len(items), list.Name) |
| 138 | c.Log.Tracef("values: %+v", items) |
| 139 | |
| 140 | txClient, err := c.Ent.Tx(ctx) |
| 141 | if err != nil { |
| 142 | return 0, fmt.Errorf("error creating transaction: %w", err) |
| 143 | } |
| 144 | |
| 145 | for _, item := range items { |
| 146 | c.Log.Debugf("adding value %s to allowlist %s", item.Value, list.Name) |
| 147 | |
| 148 | rng, err := csnet.NewRange(item.Value) |
| 149 | if err != nil { |
| 150 | c.Log.Error(err) |
| 151 | continue |
| 152 | } |
| 153 | |
| 154 | query := txClient.AllowListItem.Create(). |
| 155 | SetValue(item.Value). |
| 156 | SetIPSize(int64(rng.Size())). |
| 157 | SetStartIP(rng.Start.Addr). |
| 158 | SetStartSuffix(rng.Start.Sfx). |
| 159 | SetEndIP(rng.End.Addr). |
| 160 | SetEndSuffix(rng.End.Sfx). |
| 161 | SetComment(item.Description) |
| 162 | |
| 163 | if !time.Time(item.Expiration).IsZero() { |
| 164 | query = query.SetExpiresAt(time.Time(item.Expiration).UTC()) |
| 165 | } |
| 166 | |
| 167 | content, err := query.Save(ctx) |
| 168 | if err != nil { |
| 169 | return 0, rollbackOnError(txClient, err, "unable to add value to allowlist") |
| 170 | } |
| 171 | |
| 172 | c.Log.Debugf("Updating allowlist %s with value %s (exp: %s)", list.Name, item.Value, item.Expiration) |
| 173 | |
| 174 | // We don't have a clean way to handle name conflict from the console, so use id |
| 175 | err = txClient.AllowList.Update().AddAllowlistItems(content).Where(allowlist.IDEQ(list.ID)).Exec(ctx) |
| 176 | if err != nil { |
| 177 | c.Log.Errorf("unable to add value to allowlist: %s", err) |
| 178 | continue |
| 179 | } |
| 180 | |
| 181 | added++ |
| 182 | } |
| 183 | |
| 184 | err = txClient.Commit() |
| 185 | if err != nil { |
| 186 | return 0, rollbackOnError(txClient, err, "error committing transaction") |
| 187 | } |
| 188 | |
| 189 | return added, nil |
| 190 | } |
| 191 | |