package files import ( "crypto/rand" "encoding/hex" "strings" ) // keyRandomBytes gives 128 bits of entropy, so keys are not guessable and // collisions are negligible without a lookup before the write. const keyRandomBytes = 16 // newKey returns "/<32 lowercase hex characters>". No caller input // other than the validated policy namespace reaches the key, so file names // cannot cause path traversal or reveal personal data through object keys. func newKey(namespace Namespace) string { var random [keyRandomBytes]byte // crypto/rand.Read never returns an error; it aborts the process instead. _, _ = rand.Read(random[:]) return string(namespace) + "/" + hex.EncodeToString(random[:]) } // ownsKey accepts only keys this policy could have generated. It rejects keys // from other namespaces and any value a client could have shaped. func (policy Policy) ownsKey(key string) bool { random, ok := strings.CutPrefix(key, string(policy.namespace)+"/") if !policy.valid() || !ok || len(random) != hex.EncodedLen(keyRandomBytes) { return false } for _, char := range random { if (char < '0' || char > '9') && (char < 'a' || char > 'f') { return false } } return true }