Skip to content

Implement S3 media storage, event management, and API improvements - #279

Merged
saqibmanan merged 158 commits into
mainfrom
dev
Dec 2, 2026
Merged

saqibmanan merged 158 commits into
mainfrom
dev

Conversation

@amit0539

@amit0539 amit0539 commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Release of dev to production.

Highlights

Before this is merged (prod host, user-only)

  • STORAGE_BUCKET, STORAGE_REGION, STORAGE_ENV=prod, STORAGE_PUBLIC_BASE_URL in the prod .env (the app refuses to start without the first three; CI's sanity check uses placeholders and will not catch a missing one)
  • Instance role attached to the host, IMDS hop limit 2
  • Database dump and EBS snapshot taken
  • Frontend release (DataSpaceFrontend#573) deployed first

Checks

  • Trial merge into main: no conflicts
  • Migration graph: single chain (0064 → 0065 merge → 0066 → 0067 → 0068)
  • CI green on dev head

After deploy

  1. migrate_media_to_s3 --source /code/files/public (dry run: expect failed=0, missing near 0)
  2. Same with --execute, then search_index --rebuild -f
  3. Check an organisation logo loads from the CDN
  4. Comment out the nginx /public/files/ alias so legacy links redirect to the CDN
  5. Keep files/public on disk until prod has run on S3 for 1–2 weeks

saqibmanan and others added 30 commits October 9, 2026 19:07
A green 'Tests skipped' job records it on the run, and Finalize Deploy
still prunes images. main ignores the flag.
Run workflow on dev with 'rollback' ticked skips the build and runs the
existing rollback job, which restores the previously live image. The run
stays green when the rollback succeeds.
ci(deploy): SKIP_DEV_TESTS flag and a dev rollback button
The fallback https://api.civicdataspace.in does not resolve, so every
download_url in DCAT/Croissant/Dublin Core exports was a dead link when
PUBLIC_API_URL was unset. Use https://api.datakeep.civicdays.in, the prod
API host, in settings, the export adapter and .env.example.

Closes #238
fix(api): point PUBLIC_API_URL fallback at the live prod API
The export view caught every ValueError around export_dataset() and sent
str(exc) back with a 400, so internal errors (crosswalk, dates, rdflib)
reached anonymous users verbatim and were reported as client errors.

Validate standard and format against export_options() before exporting
and answer with a fixed message plus the options. Every other failure
now falls to the logged generic 500.

Closes #240
fix(api): stop returning exception text from metadata export
DVC never worked: uploaded files were never under DVC_REPO_PATH, so every
DVC call raised and createMajorVersion always failed. Remove the manager,
the setup command, version-change detection and the post_save signal.

createMajorVersion now writes the ResourceVersion row directly inside
transaction.atomic(), behind IsAuthenticated plus a check that the caller
owns the dataset or may change it.

BREAKING CHANGE: the setup_dvc management command and DVC_* settings are gone.
Media moves to S3 only, through django-storages. Two storages share one
bucket under <STORAGE_ENV>/public and <STORAGE_ENV>/private: public assets
get unsigned, cacheable URLs; private files get 5-minute presigned URLs.
The default storage is private, so anything that falls back to it is never
world-readable by accident. Empty access keys use the boto3 credential
chain (ECS/EC2 task role).

boto/urllib3 loggers are capped at WARNING because at DEBUG they log every
signed request, Authorization header included.

Tests swap all storages for InMemoryStorage and never reach S3.
Every FileField/ImageField now names a storage: logos, cover images,
profile pictures and publication block files go to public storage;
resource files and chart images go to private storage. The storages are
callables, so the migrations record a function reference, not bucket
settings.

upload_to paths drop their "files/public/" and "files/" prefixes, which
only repeated what MEDIA_ROOT used to add; the storages already put every
key under <env>/public or <env>/private.
S3 has no FieldFile.path, so every reader that used it would raise
NotImplementedError once media left local disk.

- local_copy() yields a temporary local copy (keeping the extension) for
  pandas, libmagic and the YAML/XML parsers; data indexing, entry counts
  and MIME validation use it.
- The lru_cache on the loaders is dropped: it keyed on temp paths that
  are deleted on exit, so it only held DataFrames in memory.
- Downloads stream with FileResponse instead of reading whole objects.
- Charts only check that the file exists; they read the indexed table.
- Search documents index the storage URL instead of a rewritten disk path.
Links issued before the move pointed at /public/<name> on disk. That route
now redirects to the file's public S3 URL, after stripping the old
"files/public/" or "files/" prefix from the name.

Only public files redirect. The old static() route also served resources
and drafts whenever DEBUG was on; anything outside public storage, or a
name that tries to traverse paths, is a 404 here.
Rows created on disk carry a "files/public/" or "files/" prefix that the
S3 keys no longer use. For each stored name the command puts the file at
the normalised key in the storage its field names, taken from the old S3
key or, with --source, from the old disk tree, then repoints the row.

Dry run by default; --execute copies and renames. Safe to re-run (names
already in place are skipped) and deletes nothing.
Regression tests for the local-disk/DVC to S3 migration: S3 storage
options (unsigned public URLs, 5-minute presigned private URLs, private
default), which storage each file field names, local_copy() and MIME
checks on storage without paths, prefix-free upload names, the legacy
/public redirect (public files only, no traversal), createMajorVersion's
owner-only version write, and migrate_media_to_s3 (dry run, disk and old
S3 sources, missing files, failed copies).
Replace the DVC references in SECURITY.md and AGENTS.md with the S3
storage layout and access rules, and add the no-co-author commit rule to
AGENTS.md.
Agents kept tripping over setup the file never mentioned (.env and logs/
are needed before tests boot; pre-commit pins python3.11) and over
S3-era rules that lived only in code review. Add a quick start, a
commands table with the SDK test command, task checklists for mutations,
model changes and bug fixes, a files-and-media section (no FieldFile.path,
local_copy, FileResponse, public vs private storage), and git safety
rules (self-contained commits, no AI co-author trailer, never stash the
user's work). Existing rules are unchanged.
CivicDataLab's scrapers fill "Source identifier" on every dataset they upload
(dataspace-scrapers/<scraper_id>/<dataset_key>) and read it back to recognise their
own datasets, so a dataset is never created twice and their upload records can be
rebuilt from DataSpace. The data migration creates the item, or switches it back on
if an admin switched it off; reversing it deletes nothing.

Tests: tests/test_source_identifier_migration.py

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…fier

feat(metadata): add source identifier dataset metadata item
…blications

Add useCasesTable, collaborativesTable, aiModelsTable and publicationsTable,
shaped like datasetsTable: client filters and sort options limited to an
allowlist per module, limit/offset paging, the total after filters, and
counts per status for the dashboard tabs (ignoring the status filter so tab
labels stay stable).

Each query shows the same rows as the module's existing list query, plus
published (for AI models: public and active) rows when includePublic is
set. The existing list queries are unchanged. StatusCount and
status_counts() are shared in api/utils/qs_utils.py. No migration.
The tab counts in datasetsTable were an inline copy of what
status_counts() in api/utils/qs_utils.py now does for the other four
tables. Call the helper instead, so all five tables count statuses in one
place. status_counts() takes an optional item_type so the dataset table
keeps its DatasetStatusCount type; the GraphQL schema is unchanged.
feat(api): table queries for use cases, collaboratives, AI models, publications
The charts dashboard loads every built chart and chart image through
getChartData and searches them in the browser. chartsTable returns one
page of both kinds in a single list, with the total count and per-status
counts, using the shared table helpers.

Both tables are merged in one SQL UNION, so counting, sorting and slicing
happen in the database; only the rows of the page are then loaded.
Visibility and permission are the same as getChartData. Rows keep their
types (TypeResourceChart, TypeResourceChartImage), so existing fragments
work unchanged. getChartData is untouched.
Sorting and paging now go through the same helper as the other table
queries. Only filtering stays per table, because Django cannot filter
after a UNION. Drops the extra id tie-breaker, matching the others.
feat(api): add chartsTable with filters, sorting and pagination
This commit introduces a new Event model with fields for name, location, dates, and status, along with a corresponding GraphQL schema for creating, updating, and querying events. The schema includes input types for event creation and updates, as well as queries for retrieving events based on various filters. Additionally, utility functions for handling Luma embeds and event permissions are implemented to ensure proper validation and access control.
An event whose owner was deleted (user set to NULL) and has no
organization was reported as individual by the API but not by
Event.is_individual_event. Use the same check in both.
Each event gets a 12-character public_id; its link is the name words
plus that id (urlSlug), so renames never break links and two events
can share a name. eventBySlug finds the event by the id at the end of
the link. The slug is no longer unique and the counter loop is gone.

Also drops the 0055_event dependency on
0049_merge_publication_and_accessmodel, which does not exist.
anantjain341 and others added 29 commits November 27, 2026 12:42
…publish

fix(search): remove unpublished collaboratives from search
fix(api): remove path from GraphQL file fields
fix(api): refuse organization names whose slug is taken
feat(api): link publication contributors to users
fix(api): keep publication fields to the platform's limits
assignOrganizationRole only checked that the caller's role could edit
content, so an editor could give the admin role to anyone, themselves
included. It now uses the same admin check as adding and removing
members, and refuses a change to the caller's own role (ids compared as
numbers, so a padded id cannot get round it).
…nd dataspaces

The sector, SDG, metadata field and dataspace create/update/delete
mutations had no permission check (deleteMetadata only asked for
sign-in), so anyone could add, rename or delete the records every
organisation's datasets, use cases and filters use. They now require a
signed-in superuser, through a new IsSuperuser permission; so do
deleteTag and deleteTags, which any signed-in user could call.
Chart reads only checked whether the caller may see the dataset. A
published dataset is public, so getChartData (the dataset page's
Visualisations tab) and the other chart queries returned its draft and
unpublished charts and chart images to anyone; unpublishing a chart
withdrew nothing.

Published charts of datasets the caller may see stay public. Draft and
unpublished charts are now shown only to people with a grant on the
dataset: owner, organisation members whose role can view, dataset
permissions, editors and superusers. The dataset search flag has_charts
now counts published charts only.
The user type is returned by user(), userById, getPublishers and the
creator and contributors of every published dataset, use case,
collaborative and publication, and it carried the email address, last
login and organisation memberships to anyone. User ids are sequential
and login names are often email addresses, so every address could be
collected without signing in.

Email, an email-shaped login name and last login are now shown only to
the user, superusers and members of a shared organisation whose role
can view it; fullName no longer falls back to an email address, and
memberships list only organisations the caller may list. user(id |
username) answers only for the caller's own account (superusers: any).
The public publisher and unified search results no longer carry users'
email addresses or email-shaped login names, the publisher search no
longer matches on them, and the user search document stops storing them.
searchUsers matches a login name that is an email address only as a whole
and returns at most 20 people, and the public metadata export and AI
model detail no longer fall back to the login name for unnamed users.
Name, picture, bio, links and location stay public.
fix(auth): only organisation admins can change member roles
…ruser

fix(api): only superusers can change sectors, SDGs, metadata fields and dataspaces
fix(api): hide draft and unpublished charts of published datasets
…elds

fix(auth): keep users' email and login details private
deleteOrganization compared the membership's role (a Role row) with the
string "admin", which is never equal, so everyone except superusers was
refused, including the organization's own admins. Compare the role name.
fix(api): let organization admins delete their organization
Every authenticated request copied given_name/family_name from the
Keycloak token onto the user. A token keeps the name it was issued with,
so the next request made with a token from before a profile edit put the
old name back (on dev, a single REST request after updateUser did it).

Take names from Keycloak only while ours are empty; email, username and
admin flags still sync on every request.
fix(auth): keep profile name edits when an older token signs in
Both publisher documents shared one get_instances_from_related that
returned a dataset's or use case's organization and its user. The
search library writes that list into the calling document's index, so
every save put the user into organization_publisher and the
organization into user_publisher. Publisher and unified search read
both indexes and showed and counted those publishers twice; where a
user and an organization share an id, the misplaced entry replaced the
real one.

Each document now returns only publishers of its own model. Migration
0069 deletes the entries already stored in the wrong index; the
release step's refill after migrate writes back any it had replaced.

Fixes #352
The replace-the-list mutations looked ids up with filter(id__in=...),
which silently leaves out ids that do not exist, then saved the shorter
list and reported success; a list of only unknown ids emptied it. The
organisation-relationship mutations also deleted the existing links
before looking anything up. updateFileResourceSchema skipped column ids
that are not columns of the resource, also reporting success.

require_all() looks up every id and refuses the call, naming the
missing ids, before anything is saved. The relationship mutations check
both lists first and replace the links in one transaction. Draft
publications are still left out of publication links on purpose.

Fixes #350
createModelEndpoint and updateModelEndpoint saved url, timeout,
retries and rate limit exactly as sent. Mutations save without
full_clean, so the model's URLField rule never ran: "not a url", a
timeout of -5 and -1 retries were all stored and reported as success.
Version providers already had these checks.

The endpoint mutations now apply the provider rules (http/https URL,
timeout 1-600) plus the URL column's length, retries 0-10 and a rate
limit of at least 1, after the permission check and before anything is
written. Create needs a URL; update checks only the fields sent and
refuses blanking a saved URL. The server never calls ModelEndpoint.url,
so there is no public-address check.

Fixes #348
organizationContributedSectors, the organisation's
contributedSectorsCount and the publisher search entry found use case
sectors only through partner/supporter links, while
organizationPublishedUseCases also lists use cases the organisation
owns. An organisation whose only use case it owned showed 0 sectors
(org 76 on dev and prod).

The rule now lives in api/utils/organization_contributions.py
(published_use_cases, contributed_sectors) and every one of these uses
it, so the sector count always comes from the same use cases the
organisation page lists.

Fixes #346
…ates

fix(search): stop listing publishers twice in publisher search
fix(api): refuse unknown ids in list mutations instead of dropping them
…ecks

fix(aimodel): check model endpoint URL and limits before saving
fix(api): count sectors of use cases an organisation owns
The API allowed every origin together with credentials, so any website
could call it from a visitor's browser and read the reply, on dev and
prod alike (both run the same settings). The API also accepts a Django
admin session cookie as a login.

Allow civicdataspace.in and its subdomains (frontend, dev, collaborative
subdomains, ParakhAI), plus whatever a server lists in
CORS_EXTRA_ORIGINS (dev: http://localhost:3000). Credentials are off:
callers sign in with the Authorization header, never with cookies.
Requests without an Origin (SDK, servers) are unaffected.
fix(api): allow CORS only from our own sites, without credentials
Linking a dataset or use case into a collaborative or use case checked
only the item being changed and loaded the linked one by id alone, and
the linked lists returned every linked item. A signed-in user could
link another organisation's draft into their own collaborative and read
its title and fields back there; use case ids are sequential.

Linking now accepts only items the caller may see, with the same rules
as getDataset and useCase(pk); anything else answers like a missing id.
The linked lists, their counts and publishers show each reader only the
items they may see, which also hides links made before this change.
Search entries carry published linked items only. Replacing a list
keeps the links the editor cannot see, since their list cannot name
them.
fix(api): only link and show datasets and use cases the caller may see

This branch was successfully deployed

1 active deployment
development — c43da0ab Deployed Dec 2, 2026 by anantjain341 via Finalize Deploy #141
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants