Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.git
.claude
*.sqlite*
117 changes: 117 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
name: CI
on:
pull_request:
merge_group:
push:
branches: [main, 'gh-readonly-queue/main/**']
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6
with:
go-version-file: go.mod
cache: true
- run: go run ./cmd/check-boundary
- run: test -z "$(gofmt -l cmd internal)"
- run: go vet ./...
- run: go test -race -count=1 ./...
- run: go test -count=10 ./internal/data -run 'TestClaimRace|TestOwnerDifferential'
image:
needs: test
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- id: tags
shell: bash
env:
EVENT: ${{ github.event_name }}
REF: ${{ github.ref }}
SHA: ${{ github.sha }}
REPO: ${{ github.repository }}
run: |
image="ghcr.io/${REPO,,}"
stamp=$(git show -s --format=%cI "$SHA" | date -u -f - +%Y%m%dT%H%M%SZ)
if [[ "$EVENT" == push && "$REF" == refs/heads/main ]]; then
echo "publish=true" >> "$GITHUB_OUTPUT"
echo "tags=$image:main-$stamp-${SHA:0:12},$image:sha-$SHA" >> "$GITHUB_OUTPUT"
else
echo "publish=false" >> "$GITHUB_OUTPUT"
echo "tags=$image:check-$SHA" >> "$GITHUB_OUTPUT"
fi
- uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
if: steps.tags.outputs.publish == 'true'
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
with:
context: .
push: ${{ steps.tags.outputs.publish == 'true' }}
tags: ${{ steps.tags.outputs.tags }}
platforms: linux/amd64
release:
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
needs: test
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
outputs:
created: ${{ steps.release.outputs.release_created }}
tag: ${{ steps.release.outputs.tag_name }}
steps:
# A fresh installation token lets release PRs start CI. The repository
# owner provisions an app credential scoped to this repository.
- uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3
id: token
with:
client-id: ${{ vars.RELEASE_APP_CLIENT_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
repositories: ${{ github.event.repository.name }}
permission-contents: write
permission-pull-requests: write
- uses: googleapis/release-please-action@5c625bfb5d1ff62eadeeb3772007f7f66fdcf071 # v4
id: release
with:
token: ${{ steps.token.outputs.token }}
release-image:
needs: [release, image]
if: needs.release.outputs.created == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ needs.release.outputs.tag }}
- uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Versioned image tag
id: tag
env:
TAG: ${{ needs.release.outputs.tag }}
REPO: ${{ github.repository }}
run: |
[[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]
echo "image=ghcr.io/${REPO,,}:$TAG" >> "$GITHUB_OUTPUT"
- uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
with:
context: .
push: true
tags: ${{ steps.tag.outputs.image }}
platforms: linux/amd64
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.claude/
*.sqlite
*.sqlite-*
/underwraps
1 change: 1 addition & 0 deletions .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{".": "0.0.0"}
10 changes: 10 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
FROM mirror.gcr.io/library/golang:1.27.3@sha256:e519d3b0a5b285e5aa53ab9eef02bc6bbb9cb04608389b743a136a9ce75f0d1e AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/underwraps ./cmd/underwraps
FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/underwraps /underwraps
USER 65532:65532
ENTRYPOINT ["/underwraps"]
30 changes: 29 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,29 @@
# underwraps
# Under Wraps

Dated, group-shared wish lists with purchases and surprise gifts kept private from
the recipient. Fresh Go implementation, Apache-2.0 licensed.

This is the M1 database and release foundation. There is no usable UI, login,
HTTP/MCP listener or deployment yet. The command initializes/migrates a database
and exits. It deliberately cannot expose a database query endpoint.

Requires Go as specified in `go.mod`. Reproduce the checks with:

```sh
go run ./cmd/check-boundary
go vet ./...
go test -race -count=1 ./...
go test -count=10 ./internal/data -run 'TestClaimRace|TestOwnerDifferential'
CGO_ENABLED=0 go build ./cmd/underwraps
```

Initialize a development database (not a server):

```sh
go run ./cmd/underwraps -database ./state/app.sqlite -timezone America/Chicago
```

See [the contract](docs/spec.md), [schema and API](docs/data.md), and
[migrations, recovery and release prerequisites](docs/operations.md).
All real identities, groups, hosts, secrets and deployment values belong in private
configuration. Examples use synthetic identities and `example.invalid` domains.
12 changes: 12 additions & 0 deletions cmd/check-boundary/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package main

import (
"github.com/frecklelabs/underwraps/internal/boundary"
"log"
)

func main() {
if err := boundary.Check("."); err != nil {
log.Fatal(err)
}
}
23 changes: 23 additions & 0 deletions cmd/underwraps/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// M1 supplies a persistence smoke command; HTTP, OIDC and MCP arrive in M2.
package main

import (
"flag"
"github.com/frecklelabs/underwraps/internal/data"
"log"
"time"
)

func main() {
path := flag.String("database", "", "private SQLite file (required)")
zone := flag.String("timezone", "", "IANA calendar timezone (required)")
flag.Parse()
s, err := data.Open(data.Config{Path: *path, Timezone: *zone, Clock: time.Now})
if err != nil {
log.Fatal(err)
}
if err = s.Close(); err != nil {
log.Fatal(err)
}
log.Print("database foundation ready; no HTTP or MCP listener in M1")
}
16 changes: 16 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

The source guard resolves the data package's local type graph across files,
including aliases, nested exported fields and embeddings. Only reviewed scalar,
DTO and injected clock types may cross the boundary. `context.Context` is
permitted only at the input positions in approved operation signatures; exported
fields, aliases, nested containers and embeddings cannot carry it because `Value`
can expose arbitrary capabilities. The built-in `error` interface is likewise
restricted to approved operation results and error sentinels, rather than DTO
fields or aliases. Interfaces and callable capabilities fail closed. Operation
signatures (including receivers and caller arguments) are an explicit reviewed allowlist. Adding or changing an API requires
updating that contract with its permission/secrecy tests. Local types cannot
shadow the predeclared types used in the approved signatures. Private Store fields
remain implementation details. Parser/AST tooling imports are restricted to the
boundary checker package; application code cannot use parser.ParseFile as an
alternate database-file opener. The guard scans tests and build-tagged files for
imports too, and checks production API declarations regardless of build tags.
80 changes: 80 additions & 0 deletions docs/data.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Data boundary and schema (schema version 1)

`internal/data` alone imports the SQLite driver and `database/sql`, opens the file,
and runs migrations. `Store.db` is unexported. No operation returns SQL, handles,
rows, connections or callbacks. `Config` requires a private path, a valid IANA
calendar timezone, an injected clock and optional configured administrator
issuer/subject pairs. Identity verification belongs to M2: callers must not
construct identities from unverified request parameters. Display names convey no
permission. The application owns one Store and one mounted database directory.

The source guard parses **every** `.go` file, including tests, nested directories
and excluded build tags. Outside the data package it uses an import allowlist,
rejects drivers and SQL imports (including aliases/dot imports), blocks filesystem
open/read/write references and HTTP file-serving helpers, and rejects unreviewed
data exports and exported SQL-bearing types/signatures. Only the guard's two
source files can read/write files for source inspection/negative fixtures.
Changing this allowlist or persistence package is a boundary change requiring
review; it is not a sandbox against someone editing the guard itself.

| Record | Key and purpose |
| --- | --- |
| users | Integer ID; unique verified issuer + subject; display name, disabled marker |
| groups | Configured group ID/name and disabled marker |
| memberships | Group/user pair and active marker |
| lists | ID, owner, name, occasion date, owner-visible creation/update times and revision |
| shares | List/group pair and active marker |
| items | Random 63-bit ID, list, creator, surprise flag, original requested fields, priority, creation/update times, revision, deleted marker |
| claims | Item key, buyer and active marker; an atomic upsert wins only when unclaimed |
| coordination | Append-only item/actor/action/time history of claim and release transitions |

Foreign keys are enabled. Schema initialization and the version marker are one
transaction. No physical record deletes are used. List archive status is computed
from the injected clock in the configured timezone: the occasion remains writable
through 23:59:59 local time and archives at the following midnight. Moving an
already archived list forward is rejected too.

Every operation below takes `context.Context` and the verified viewer `Identity`.
The only lifecycle operations are `Open(Config)` and `Close()`.

| Operations | Permission and result |
| --- | --- |
| Register | Registers only caller's verified identity; cannot reactivate a disabled user |
| Users, Groups | Configured, active administrators only; user/group metadata, never content |
| SetUser, CreateGroup, SetGroup, SetMembership | Same admin requirement; disabled/active markers retain records |
| CreateList | Caller owns it and must be an active member of every shared group |
| UpdateList | Active-list owner; same sharing checks; replaces shares using active markers |
| Lists | Authorized discovery, active/archive filter, summary counts, stable occasion/ID order, bounded offset/limit |
| ListDetail | Authorized owner or active member of an active shared group; priority descending then item ID ascending |
| DeletedItems | Owner only; original requested-item fields, no coordination projection |
| AddRequest, UpdateRequest, DeleteRequest, RestoreRequest | Active-list owner; bounded to list and requested-item ID; return OwnerItem |
| AddSurprise | Active-list authorized non-owner; returns new hidden ID |
| Claim, ReleaseClaim | Active-list authorized non-owner; self-claim rejected; only buyer can release |
| DeleteSurprise | Active-list creator, still authorized non-owner; soft deletion |

A list owner can access their own list even if their group membership changes.
Other viewers need a current membership and active share/group on every operation.
Admin status grants no content bypass. Unknown, unauthorized, cross-list and
hidden IDs use the same `ErrMissing`. Visibility is checked before page/input
validation. A known authorized archived list returns `ErrArchived` on mutations;
unauthorized list IDs still return `ErrMissing`. Pages require offset >= 0 and
1 <= limit <= 100. Errors expose no buyer data. Request validation requires a
nonblank name, positive quantity and nonnegative priority; prices are display
strings, not currency arithmetic. URLs are stored, never fetched by this package.

`View` contains exactly one of `OwnerView` and `MemberView`; the other JSON field
is omitted. `OwnerItem` has only requested fields and owner-controlled metadata.
Owner SQL has `surprise=0` and the chosen deleted marker in both count and page
queries; it never joins claims. Member queries include active items and bought
owner-deleted requests, with buyer and removed-by-owner metadata. A removed bought
request is presented as a surprise to members while its original requested record
is retained for owner restore. Coordination never updates owner item/list metadata.
Random item IDs avoid leaking hidden inserts through sequence gaps.

Tests use real temporary on-disk SQLite databases. The read matrix covers owner,
members, non-member and non-member admin, each item state, and active/archive
status. Additional tests cover discovery/counts/pages/order, cross-group/list IDs,
membership revocation, admin isolation, archive midnight, buy races across two
Store instances, persistence and migrations. Differential tests clone identical
on-disk starting worlds and compare complete serialized owner responses and
mutation/error results with and without hidden purchases and surprises.
77 changes: 77 additions & 0 deletions docs/operations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Migrations, recovery and releases

This milestone is a library plus a smoke command. It neither runs a server nor
provides a database query endpoint. Do not deploy the M1 command as a service.
The deployment milestone must mount the persistent directory only in the app,
with one replica, no query sidecar/service and no external DB MCP endpoint.
Secrets, issuer, subjects, groups, hostname, exposure, timezone and storage values
are private deployment configuration. There are no real values in this repo.

SQLite uses foreign keys, a 5-second busy timeout and one connection per Store.
The service is designed for one app process/replica, using a Store mutex around
permissions and operations; transactions cover multi-record changes and claims.
An atomic claim upsert also prevents two Store instances from winning one claim.
Mount local persistent storage with SQLite-compatible locking, not an arbitrary
shared network filesystem. Set restrictive directory/file ownership for the
nonroot image user; `Open` creates new directories 0700 and new files 0600, but
does not fix pre-existing directory/file permissions. Do not expose this directory
through HTTP static file serving. The timezone is mandatory; tests cover the
America/Chicago midnight boundary. The Go binary embeds the IANA timezone data.

## Schema and rollback

The current schema is version 1 (`PRAGMA user_version`). New databases get all
DDL and the version marker in a single transaction. Reopening version 1 is a
no-op. A newer schema is refused, rather than silently opened by older code.
Future schema changes must be ordered, transactional migrations with fixture
upgrade tests. Prefer additive changes compatible with the previous binary;
do not silently migrate backward, drop records or discard coordination history.

Before any future migration, stop the single writer, copy the **whole database
and any journal/WAL companions** into a private protected backup, and verify it
opens and passes an integrity check using a controlled recovery tool inside the
data boundary. Never upload backups or real content to this repository. Rehearse
recovery on a synthetic copy first. This milestone has no production data and
no backup/recovery endpoint.

For binary-only rollback on compatible schema, stop the writer and restore the
previous image digest. For incompatible migration rollback, keep the current
database intact, restore the pre-migration backup into a separate directory,
and start the prior binary against that copy. Verify identity/membership,
owner secrecy, buyer coordination, read-only archives and persistence before
switching traffic. Restoring an older snapshot loses later writes; obtain the
owner's decision before any destructive recovery. There are no automatic down
migrations or automated data deletion commands.

## CI and publication

Use Conventional Commit subjects, e.g. `feat: add list priorities` or
`fix: preserve claims on restore`. Release-please tracks `version.txt`,
`.release-please-manifest.json` and `CHANGELOG.md` with simple releases. The first
release starts from 0.0.0. Workflow changes require owner review.

CI runs the source boundary check with negative fixtures, formatting, vet, the
real SQLite tests under the race detector, repeated claim/differential checks,
and a container build. It triggers for pull requests, merge groups, and queue
branch pushes, with valid `check-<full-SHA>` tags; those builds never publish.
Every main push independently publishes `sha-<full-SHA>` and
`main-<UTC-commit-time>-<12-char-SHA>`. No moving `main` or `latest` tag is used.
The deployment can select the sortable main tags and pin a digest for rollback.
Release-please runs separately from main image publishing; a missing release
credential cannot prevent the main image job. On a release, the same workflow
checks out the returned version tag and publishes `v<major>.<minor>.<patch>`.
It does not rely on a second release event from GITHUB_TOKEN.

The repository owner must provision `vars.RELEASE_APP_CLIENT_ID` and
`secrets.RELEASE_APP_PRIVATE_KEY` for an approved GitHub App installation scoped
to this repository with contents and pull-request write permission. The workflow
mints and later revokes a fresh installation token; no expiring token is stored
as a static secret. A plain GITHUB_TOKEN would create release PRs that do not
trigger CI. No credential or App is created by this milestone. Until those
prerequisites are seeded, release automation is not verified. GHCR publication
also needs repository package write permission.

M1 local test/build results are evidence only for source behavior. After merge,
verify actual main image publishing by commit and digest, then a release PR and
versioned image. First live acceptance, persistent storage, deployment rollback,
OIDC/HTTP/MCP caller identity and browser behavior belong to later milestones.
Loading
Loading