| 1 | package hostops |
| 2 | |
| 3 | import ( |
| 4 | "crypto/sha256" |
| 5 | "encoding/hex" |
| 6 | "fmt" |
| 7 | "strings" |
| 8 | |
| 9 | "github.com/carlosframework/platform/internal/geoip" |
| 10 | ) |
| 11 | |
| 12 | // classifyGeoip reviews the whole control/geoip/ family, exactly, as operator |
| 13 | // platform state that holds no app record: the content-addressed database |
| 14 | // blobs, the pointer to the live one, and the feed's status file. Nothing |
| 15 | // else under the prefix is classified, and a body that is not what the |
| 16 | // publisher writes at that key is refused, so a stray write cannot ride the |
| 17 | // family. Deletes carry no body and are checked by key alone. |
| 18 | func classifyGeoip(t MutationTarget) (Classification, error) { |
| 19 | deleting := t.Method != "Put" |
| 20 | switch { |
| 21 | case t.Key == geoip.PointerKey: |
| 22 | if !deleting { |
| 23 | if _, err := geoip.ParsePointer(t.After); err != nil { |
| 24 | return Classification{}, fmt.Errorf("%w: %s: %v", ErrUnclassified, t.Key, err) |
| 25 | } |
| 26 | } |
| 27 | return Classification{Family: "geoip-pointer", NonApp: "operator GeoIP pointer; names one platform database blob and holds no app record"}, nil |
| 28 | case t.Key == geoip.FeedKey: |
| 29 | if !deleting { |
| 30 | if _, err := geoip.ParseFeedStatus(t.After); err != nil { |
| 31 | return Classification{}, fmt.Errorf("%w: %s: %v", ErrUnclassified, t.Key, err) |
| 32 | } |
| 33 | } |
| 34 | return Classification{Family: "geoip-feed", NonApp: "operator GeoIP feed status; holds no app record"}, nil |
| 35 | case IsGeoipBlobKey(t.Key): |
| 36 | // A streamed put has no body here (PutFrom): the publisher hashed it |
| 37 | // while staging and a create-only put cannot replace an object. A |
| 38 | // buffered one must hash to its own name. |
| 39 | if !deleting && len(t.After) != 0 { |
| 40 | sum := sha256.Sum256(t.After) |
| 41 | if t.Key != geoip.BlobKey(hex.EncodeToString(sum[:])) { |
| 42 | return Classification{}, fmt.Errorf("%w: %s: body does not hash to its name", ErrUnclassified, t.Key) |
| 43 | } |
| 44 | } |
| 45 | return Classification{Family: "geoip-blob", NonApp: "operator GeoIP database blob, content-addressed by its sha256; holds no app record"}, nil |
| 46 | } |
| 47 | return Classification{}, fmt.Errorf("%w: %s", ErrUnclassified, t.Key) |
| 48 | } |
| 49 | |
| 50 | // IsGeoipBlobKey is exactly control/geoip/<64 lower-case hex>.mmdb. |
| 51 | func IsGeoipBlobKey(key string) bool { |
| 52 | rest, ok := strings.CutPrefix(key, geoip.Prefix) |
| 53 | if !ok { |
| 54 | return false |
| 55 | } |
| 56 | sha, ok := strings.CutSuffix(rest, ".mmdb") |
| 57 | return ok && geoip.IsSHA256Hex(sha) |
| 58 | } |
| 59 | |