package memory import ( "fmt" "regexp" "strings" "unicode/utf8" "github.com/samcharles93/archie-core/internal/webhookguard" ) // maxNoteLength bounds a note: a remembered fact is a sentence or two, not a // document. const maxNoteLength = 2000 // redacted replaces a secret-shaped value inside a note. const redacted = "[redacted]" var ( // credentialAssignment is a credential written out with its value: a // credential, not a fact about one. credentialAssignment = regexp.MustCompile(`(?i)\b(pass(word|phrase)?|secret|token|api[ _-]?key|private[ _-]?key|client[ _-]?secret|signing[ _-]?key)\b\s*[:=]\s*\S+`) // tokenShape is a value shaped like an issued credential, inside a note // that is otherwise a fact. tokenShape = regexp.MustCompile(`(?i)\b(?:sk|pk|rk|gh[pousr]|xox[abps])[-_][A-Za-z0-9_-]{12,}|\bAKIA[0-9A-Z]{16}\b|\bbearer\s+[A-Za-z0-9._~+/=-]{12,}|\b[A-Za-z0-9_+/=-]{40,}\b`) // securityOverride is an instruction that would turn a control off. A note // is a fact, never a change to how decisions are reached, so it is refused. securityOverride = regexp.MustCompile(`(?i)ignore (all )?(the )?(previous|prior|earlier) (instruction|rule)|without (asking|approval|confirmation)|auto[- ]?approv|always (approve|allow|permit)|skip (the )?(approval|confirmation)|bypass (the )?(approval|policy|check|guard)|disable (the )?(guard|policy|approval)|no need to (ask|confirm)`) ) // minimised returns the text to store for a note, or an error when the text is // not a memory at all. Secret-shaped values are redacted before the note is // first stored, never at summarisation time, and a note that is a credential or // an instruction overriding a security control is refused. func minimised(text string) (string, error) { text = strings.TrimSpace(text) switch { case text == "": return "", fmt.Errorf("%w: a note needs text", ErrInvalidNote) case utf8.RuneCountInString(text) > maxNoteLength: return "", fmt.Errorf("%w: a note is at most %d characters", ErrInvalidNote, maxNoteLength) case securityOverride.MatchString(text): return "", fmt.Errorf("%w: a note cannot change how a decision is reached", ErrInvalidNote) case credentialAssignment.MatchString(text): return "", fmt.Errorf("%w: a note never holds a credential", ErrInvalidNote) } out := redact(text) if strings.Trim(out, " \t.:;,!?\"'") == redacted { return "", fmt.Errorf("%w: a note never holds a credential", ErrInvalidNote) } return out, nil } // redact replaces every secret-shaped span in text with a marker, keeping the // prose around it. The JWT and private-key shapes are the webhook guard's, // because they are the same problem. func redact(text string) string { return tokenShape.ReplaceAllString(webhookguard.RedactText(text), redacted) }