Files
StarPunk/docs/standards/cookie-naming-convention.md
T
PhilandClaude Opus 5.5 0716984958 docs: Bring all documentation up to date for v2.10.1
- architecture/: overview, technology stack, auth (OIDC + built-in
  IndieAuth), syndication (POSSE) rewritten; new database.md,
  deployment.md and indieweb-protocols.md; legacy stack marked historical
- decisions/: reconstructed ADR-060 and ADR-063; 31 status corrections
  (superseded auth ADRs, proposed -> accepted); INDEX rebuilt
- design/: reconstructed the v1.6.0 documents the webmention code cites;
  reports for 18 v2 releases without a design folder; INDEX rebuilt
- projectplan/: BACKLOG rewritten (shipped items removed, open issues from
  the reviews added); RELEASE.md for v2.0.0-v2.10.1; INDEX
- standards/: development setup (uv, tests, DEV_MODE), testing (CI test
  stage), git and release flow, versioning, coding standards, cookies
- README, CLAUDE.md, .env.example (every setting the code reads, with
  defaults) brought up to date
- 137 broken links repaired (old absolute paths, moved files); stale ADR
  references in code comments corrected (comments only)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:40:19 -07:00

249 lines
8.2 KiB
Markdown

# Cookie Naming Convention
**Status**: Active
**Date**: 2025-11-18
**Last Updated**: 2026-11-03 (v2.10.1; cookie list checked against the code)
**Version**: 1.1
## Purpose
This document establishes the naming convention for HTTP cookies in StarPunk to prevent conflicts with web framework reserved names and ensure clear ownership of cookie data.
## Standard
All StarPunk application cookies **MUST** use the `starpunk_` prefix to avoid conflicts with framework-reserved names.
## Rationale
**Problem**: Cookie name collision between application cookies and framework cookies can cause unexpected behavior. In Phase 4, we discovered that using a cookie named `session` conflicted with Flask's server-side session mechanism, causing an authentication redirect loop.
**Solution**: Namespace all application cookies with an application-specific prefix.
## Reserved Names (DO NOT USE)
The following cookie names are reserved by frameworks and libraries. StarPunk MUST NOT use these names:
### Flask Framework
- `session` - Reserved for Flask's server-side session (used by flash messages, session storage)
### Common Auth Frameworks
- `csrf_token` - Common CSRF protection cookie name
- `remember_token` - Common "remember me" authentication
- `auth_token` - Generic authentication token
### Generic Reserved Names
Avoid any single-word generic names that might conflict with frameworks or browsers:
- `token`
- `user`
- `id`
- `data`
- `state`
## StarPunk Cookie Names
All StarPunk cookies use the `starpunk_` prefix for clear ownership.
### Current Cookies
| Cookie Name | Set by | Purpose | Security Attributes | Max Age |
|-------------|--------|---------|---------------------|---------|
| `starpunk_session` | `/auth/callback` (`starpunk/routes/auth.py`, constant `SESSION_COOKIE`) | Admin session token (the token's hash is stored in the `sessions` table) | HttpOnly, SameSite=Lax, Secure when `SITE_URL` starts with `https://` | `SESSION_LIFETIME` days (default 30) |
| `starpunk_session` | `/dev/login` (`starpunk/routes/dev_auth.py`, only with `DEV_MODE=true`) | Same cookie, created without authentication | HttpOnly, SameSite=Lax, never Secure | 30 days (fixed) |
`starpunk_session` is read in `starpunk/auth.py` (`require_auth`),
`starpunk/routes/auth.py`, `starpunk/routes/indieauth.py` (consent screen)
and `starpunk/__init__.py` (`before_request`, so every page knows whether
the owner is logged in), and deleted on logout.
Not cookies: the OIDC login state, nonce and PKCE verifier are kept
server-side in the `oidc_login_state` table, and Micropub clients
authenticate with bearer tokens (`indieauth_tokens` table), never cookies.
### Future Cookies
All future cookies must:
1. Use `starpunk_` prefix
2. Be documented in this table
3. Have explicit security attributes defined
4. Be reviewed for conflicts with framework conventions
**Example future cookies**:
- `starpunk_preferences` - User preferences (if added)
- `starpunk_analytics` - Analytics consent (if added)
- `starpunk_theme` - Theme selection (if added)
## Security Attributes
All StarPunk cookies MUST specify these security attributes:
### Required Attributes
**HttpOnly**:
- Use for authentication and sensitive cookies
- Prevents JavaScript access
- Mitigates XSS attacks
**Secure**:
- Use in production (HTTPS)
- Can be `False` in development (HTTP)
- Prevents transmission over unencrypted connections
**SameSite**:
- Use `Lax` or `Strict`
- Prevents CSRF attacks
- `Lax` allows top-level navigation with cookie
- `Strict` never sends cookie cross-site
**Max-Age**:
- Always set explicit expiry
- Don't rely on session cookies (cleared on browser close)
- Choose appropriate lifetime for use case
### Example
```python
response.set_cookie(
"starpunk_session", # Name with prefix
session_token, # Value
httponly=True, # Prevent JS access
secure=is_production, # HTTPS only in prod
samesite="Lax", # CSRF protection
max_age=30 * 24 * 60 * 60, # 30 days
)
```
## Implementation Checklist
When adding a new cookie:
- [ ] Name uses `starpunk_` prefix
- [ ] Name doesn't conflict with framework/library cookies
- [ ] Purpose is documented in this file
- [ ] Security attributes are explicitly set
- [ ] HttpOnly is used for sensitive data
- [ ] Secure is conditional on production vs development
- [ ] SameSite is set (Lax or Strict)
- [ ] Max-Age is appropriate for use case
- [ ] Cookie is reviewed by architect
- [ ] Tests verify cookie behavior
- [ ] Cookie is documented in API contracts
## Reading Cookies
When reading cookies, always use the full prefixed name:
```python
# Correct
session_token = request.cookies.get("starpunk_session")
# Incorrect - missing prefix
session_token = request.cookies.get("session")
```
## Deletion
When deleting cookies, use the same name that was used to set them:
```python
# Correct
response.delete_cookie("starpunk_session")
# Incorrect - missing prefix
response.delete_cookie("session")
```
## Framework Cookie Coexistence
StarPunk and Flask cookies can coexist without conflict:
**StarPunk cookies**:
- `starpunk_session` - Application authentication
**Flask cookies** (framework-managed):
- `session` - Flask's signed session cookie (signed with `SECRET_KEY`, which
defaults to `SESSION_SECRET`). StarPunk stores flash messages and
`session["next"]`, the page to return to after login (set by
`require_auth` and the IndieAuth consent screen). Keep it to small,
non-secret values: it is signed, not encrypted.
Both are necessary and serve different purposes. Do not interfere with Flask's `session` cookie.
## Migration Notes
### Version 0.5.1 Migration
**Breaking Change**: Authentication cookie renamed from `session` to `starpunk_session`.
**Impact**: All existing authenticated users were logged out and needed to re-authenticate.
**Reason**: Fix critical authentication redirect loop caused by cookie name collision.
**Future Migrations**: If cookie names need to change, consider:
1. Dual-cookie period (read from both old and new)
2. Client-side cookie migration via JavaScript
3. Clear documentation of breaking change
4. User communication about re-authentication
## Validation
### During Development
- Review cookie names in code review
- Check for `starpunk_` prefix
- Verify security attributes are set
- Test with browser DevTools → Application → Cookies
### During Testing
- Automated tests should verify cookie names
- Integration tests should check cookie attributes
- Browser tests should verify cookie behavior
### Example Test
```python
def test_auth_cookie_name(client):
"""Test authentication uses correct cookie name (app built with DEV_MODE=True)"""
response = client.post("/dev/login")
# Verify correct cookie name
assert "starpunk_session" in response.headers.getlist("Set-Cookie")
# Verify does not use reserved name
cookies_str = str(response.headers.getlist("Set-Cookie"))
assert "session=" not in cookies_str or "starpunk_session=" in cookies_str
```
## References
### Internal Documentation
- **Auth Redirect Loop Fix**: `docs/design/v1.0.0/2025-11-18-auth-redirect-loop-fix.md`
- **ADR-011**: Development Authentication Mechanism
- **ADR-064**: OIDC admin login and built-in IndieAuth server (replaced ADR-005, IndieLogin, in v2.0.0)
### External Standards
- [RFC 6265 - HTTP State Management Mechanism (Cookies)](https://tools.ietf.org/html/rfc6265)
- [Flask Session Documentation](https://flask.palletsprojects.com/en/latest/api/#flask.session)
- [OWASP Session Management Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html)
## History
### Version 1.1 (2026-11-03)
- Cookie table checked against v2.10.1: `starpunk_session` lifetime follows
`SESSION_LIFETIME`, Secure follows the `SITE_URL` scheme; dev login cookie
listed; Flask `session` contents and server-side OIDC state documented
- References updated (reports folder no longer exists; ADR-064 replaced ADR-005)
### Version 1.0 (2025-11-18)
- Initial version
- Established `starpunk_` prefix convention
- Documented reserved names
- Added security attribute requirements
- Created as part of auth redirect loop fix (v0.5.1)
---
**Document Owner**: StarPunk Architecture Team
**Last Updated**: 2026-11-03
**Status**: Active Standard