Skip to content
tempkey ← Back to blog

Tempkey Blog

When Freelancers Touch Event Streams: Managing Contractor Access to Google Cloud Pub/Sub

Learn how to provision scoped, temporary permissions for external developers across Google Cloud Pub/Sub topics and subscriptions without exposing core streaming data.

Effectively managing contractor access to Google Cloud Pub/Sub requires isolating event streams at the resource level, enforcing short-lived identity federation, and continuously pruning orphaned consumer subscriptions. Without tight perimeter boundaries, external developers working on asynchronous pipelines can inadvertently expose proprietary event streams, exhaust message retention buffers, or leave unmonitored backdoors into your cloud data bus.

Event-driven topologies fundamentally change data access dynamics. In a traditional synchronous REST environment, a client requests a specific record and leaves behind an immediate access log. In contrast, Google Cloud Pub/Sub decouples publishers from consumers, allowing asynchronous message ingestion, long-term buffering, and fan-out distribution across distributed services. When external specialists, contract engineers, or agency developers build consumers or publish telemetry into this messaging layer, traditional network firewalls and static credentials fall short. Securing these touchpoints demands rigorous identity orchestration, contract-based payload schemas, and programmatic offboarding mechanisms.

The Core Data Security Risks in Cloud Messaging Pipelines

Asynchronous event architectures introduce distinct data leakage vectors that differ sharply from point-to-point HTTP APIs. When a microservice pushes a payload to a Pub/Sub topic, that message can be stored for up to 31 days depending on topic and subscription configuration. If a contractor creates a persistent subscription to an operational topic, every downstream message published to that topic—including customer PII, internal financial events, or operational secrets—remains accessible to that consumer until the subscription is drained or removed. This asynchronous decouple means an unauthorized consumer can siphon message streams silently in the background without making direct, real-time requests to an upstream production database.

A second major vulnerability is uncontrolled message retention and financial egress. Pub/Sub subscriptions pull and retain messages until an explicit acknowledgment ( ack ) is issued. If a freelancer provisions an experimental or poorly instrumented consumer that continually fails to acknowledge messages, Pub/Sub retains those payloads based on the subscription's message retention duration, which defaults to seven days. This leads to subscription message backlogs, excessive message storage billing, and massive duplicate delivery spikes when the acknowledgment deadline expires. Worse, if a contractor points an unauthenticated or loosely configured external subscriber to your project, high-throughput topics can cause substantial egress charges as data is pulled out of your Google Cloud region.

The most pervasive failure mode in growth-stage engineering teams is binding broad project-level IAM roles instead of granular resource-level topic bindings. Assigning permissions like roles/editor or roles/pubsub.editor at the Google Cloud project root gives a freelancer the ability to inspect every topic, read from every subscription, create rogue snapshots, and alter dead-letter configurations across the entire environment. Restricting the blast radius requires scoping permissions exclusively to the specific topics, subscriptions, and schemas relevant to the freelancer's active scope of work.

Essential Pub/Sub IAM Roles for Contractors and Least-Privilege Scoping

Google Cloud delivers a set of predefined roles tailored to event streaming workflows. Understanding the distinction between topic-level publishing and subscription-level pulling is critical when configuring Pub/Sub predefined IAM roles and permissions for third-party workers.

When selecting pub/sub iam roles for contractors , often default to the narrowest operational requirement:

  • Pub/Sub Publisher (roles/pubsub.publisher): Grants pubsub.topics.publish. This role allows an identity to publish messages to a specific topic but strictly denies the ability to list topics, create subscriptions, or inspect other published payloads. This is the optimal role for freelancers building upstream webhook emitters or microservice producers.
  • Pub/Sub Subscriber (roles/pubsub.subscriber): Grants permissions to consume messages (pubsub.subscriptions.consume), acknowledge delivery (pubsub.subscriptions.acknowledge), and modify ack deadlines. Crucially, it does not grant permissions to create or alter subscriptions unless combined with metadata creation permissions.
  • Pub/Sub Viewer (roles/pubsub.viewer): Grants read-only access to view configurations, message schemas, and topic/subscription metadata (such as retention duration or dead-letter targets) without granting rights to consume actual message payloads or publish data.

Under no circumstances should the Pub/Sub Admin role (roles/pubsub.admin) be assigned to external developers, external contractor accounts, or third-party service identities. The Admin role allows full control over the Pub/Sub control plane, including deleting topics, altering access control policies, attaching unauthorized push endpoints, and manipulating cryptographic keys.

Designing Custom IAM Roles for Targeted Contractor Tasks

Predefined roles are often too coarse for specific operational tasks, such as schema validation or monitoring dead-letter queues (DLQs). For example, if a contract engineer needs to debug why invalid payloads are failing serialization against an Apache Avro schema, they do not need payload subscription access to production topics. Instead, you can craft a custom IAM role that restricts their visibility solely to schema definitions:

title: "Contractor Schema Inspector"
description: "Allows contractors to view and validate Pub/Sub schemas without data access"
stage: "GA"
includedPermissions:
  - pubsub.schemas.get
  - pubsub.schemas.list
  - pubsub.schemas.validate

Similarly, for dead-letter triage, contractors should only be granted subscriber privileges on the specific dead-letter topic subscription (e.g., orders-dlq-sub), ensuring they cannot inspect healthy transactions passing through primary business topics.

Technical Implementation: Managing Contractor Access to Google Cloud Pub/Sub Topics

Properly managing contractor access to Google Cloud Pub/Sub requires moving past the web console and codifying access rules within infrastructure-as-code (IaC) or targeted command-line scripts. By declaring topic-level bindings directly, you ensure that external principals possess zero ambient project privileges.

Resource-Level Topic Binding via gcloud CLI

To grant an external contractor the ability to publish exclusively to a designated staging topic, bind the pubsub.publisher role directly to that topic resource rather than granting it at the project layer:

# Grant topic-specific publisher access to a contractor
gcloud pubsub topics add-iam-policy-binding projects/core-platform-prod/topics/contractor-ingest \
    --member="user:freelance-developer@external-agency.com" \
    --role="roles/pubsub.publisher"

For automated deployments, enforce these boundaries using Terraform. The google_pubsub_topic_iam_member resource applies authoritative bindings to a specific topic without wiping out concurrent bindings:

resource "google_pubsub_topic" "external_ingest" {
  name                       = "contractor-telemetry-events"
  message_retention_duration = "86400s" # 24 hours
}

resource "google_pubsub_topic_iam_member" "contractor_publisher" {
  project = "core-platform-prod"
  topic   = google_pubsub_topic.external_ingest.name
  role    = "roles/pubsub.publisher"
  member  = "user:freelance-developer@external-agency.com"
}

Restricting Subscription Creation

A frequent loophole occurs when contractors are granted permission to create subscriptions (pubsub.subscriptions.create) without restriction. If an identity possesses subscription creation rights at the project level, it can create a pull subscription on any topic in the project—effectively bypassing read restrictions on sensitive streams.

To mitigate this, manage subscription provisioning internally. DevOps teams should pre-create the subscription resource (e.g., contractor-telemetry-sub) attached strictly to the authorized topic, and subsequently bind roles/pubsub.subscriber only to that created subscription:

gcloud pubsub subscriptions add-iam-policy-binding projects/core-platform-prod/subscriptions/contractor-telemetry-sub \
    --member="user:freelance-developer@external-agency.com" \
    --role="roles/pubsub.subscriber"

Enforcing Time-Bound Windows with IAM Conditions

To prevent access credentials from persisting past contract milestones, use Google Cloud IAM Conditions to attach programmatic expiration timestamps directly to IAM policy bindings. This ensures that even if an administrator forgets to manually revoke access, the Google Cloud policy engine automatically denies authorization requests after the cut-off date.

The following Terraform example demonstrates an IAM condition that limits a contractor's subscriber access to a 30-day window ending on October 31, 2026, while also ensuring requests originate from a specific enterprise CIDR block:

resource "google_pubsub_subscription_iam_member" "conditional_subscriber" {
  subscription = "projects/core-platform-prod/subscriptions/contractor-staging-sub"
  role         = "roles/pubsub.subscriber"
  member       = "user:freelance-developer@external-agency.com"

  condition {
    title       = "Contract Milestone Access Window"
    description = "Expires contractor access automatically after contract delivery"
    expression  = <<-EOT
      request.time < timestamp("2026-10-31T23:59:59Z") &&
      request.time > timestamp("2026-10-01T00:00:00Z")
    EOT
  }
}

Securing Event-Driven Architecture for Freelancers: Filtering, Schemas, and Dead-Letter Queues

Access control is not limited to IAM permissions; data-plane boundaries within the message broker are equally critical when securing event-driven architecture for freelancers. By validating schemas, filtering payloads, and isolating failures, you prevent unvetted code from polluting downstream consumers or leaking sensitive operational data.

Enforcing Structural Contracts with Pub/Sub Schemas

Contractors working on producer microservices should rarely be allowed to publish arbitrary, unstructured JSON strings directly to shared topics. Doing so invites message-poisoning vulnerabilities where downstream consumer microservices crash due to missing fields, type mismatches, or unexpected null bytes.

Google Cloud Pub/Sub allows you to bind Apache Avro or Protocol Buffer (Protobuf) schemas directly to a topic. When a schema is attached with an ENFORCE validation policy, the Pub/Sub broker parses the incoming payload against the schema definition before accepting the message. If the freelancer's code publishes a payload that fails validation, the publish API returns an error, preventing corrupt data from ever reaching the bus.

// Example Avro Schema: contractor-payload-schema.avsc
{
  "type": "record",
  "name": "TelemetryEvent",
  "namespace": "com.company.events",
  "fields": [
    {"name": "event_id", "type": "string"},
    {"name": "timestamp", "type": "long"},
    {"name": "source_module", "type": "string"},
    {"name": "payload_version", "type": "string"}
  ]
}

You can create and attach this schema using the Google Cloud CLI:

# 1. Create the schema resource
gcloud pubsub schemas create telemetry-schema \
    --type=AVRO \
    --definition-file=contractor-payload-schema.avsc

# 2. Attach the schema to the ingestion topic
gcloud pubsub topics create contractor-telemetry-events \
    --schema=telemetry-schema \
    --message-encoding=JSON

Message Filtering at the Subscription Layer

If a freelancer is commissioned to optimize an order processing engine, they rarely need to receive production records containing live credit card tokens or customer street addresses. Instead of provisioning an entirely separate cluster, you can use native subscription message filtering to ensure the freelancer's subscription receives only sanitized or synthetic events.

When filtering is enabled on a subscription, Pub/Sub checks message attributes before routing payloads to the consumer. Messages that do not match the filter are automatically acknowledged and discarded by the messaging broker without hitting the contractor's consumer endpoint or incurring egress bandwidth costs:

gcloud pubsub subscriptions create contractor-orders-debug-sub \
    --topic=projects/core-platform-prod/topics/order-events \
    --message-filter='attributes.environment = "sandbox" AND attributes.synthetic = "true"'

By enforcing this pattern, operational teams allow external engineers to develop against live event brokers without granting them access to production-tier message payloads.

Dead-Letter Queues and Poison Message Isolation

When testing custom subscriber code, contractor-authored consumers may fail to handle specific edge cases, resulting in infinite consumer retry loops. To safeguard production topics, often configure a dead-letter topic (DLQ) with a strict delivery attempt threshold:

# Configure a dead-letter policy on the contractor's subscription
gcloud pubsub subscriptions update contractor-orders-debug-sub \
    --dead-letter-topic=projects/core-platform-prod/topics/contractor-orders-dlq \
    --max-delivery-attempts=5

If the contractor's consumer crashes five consecutive times on a given message, the Pub/Sub broker unroutes that message to contractor-orders-dlq. This allows a separate subscription attached to a dead-letter topic to receive undeliverable messages for analysis and offline debugging.

Authentication Patterns: Service Account Keys vs. Short-Lived Credentials

The distribution of long-lived service account JSON keys represents one of the most critical security liabilities in cloud engineering. According to guidance in the Google Cloud service account security best practices, downloadable private keys bypass central identity lifecycle controls, are frequently committed to public version control repositories, and remain completely functional after a contractor leaves an organization unless manually rotated.

Authentication Pattern Credential Lifetime Key Exfiltration Risk Operational Overhead
Exported JSON Service Account Keys Exported JSON service account keys never expire by default and remain valid until manually deleted, unless restricted by an organization policy constraint. Exported JSON service account keys are powerful credentials that can present a security risk if they are not managed correctly. Exported JSON service account keys carry an ongoing maintenance and security burden that Workload Identity Federation eliminates.
Workload Identity Federation By default, credentials generated through Workload Identity Federation are short-lived access tokens that automatically expire. Zero (no persistent cloud secrets generated) Low (mapped directly to external Git providers)
Service Account Impersonation Configurable (up to 1 hour) Minimal (tied to audited corporate identity) Medium (requires IAM impersonation bindings)

Workload Identity Federation for External CI/CD Pipelines

If an agency or freelancer is writing code that deploys through external CI/CD runners like GitHub or GitLab, configure Workload Identity Federation to access Google Cloud resources via federated identities rather than exporting a service account key. Instead, configure Workload Identity Federation. This allows the external CI/CD provider to exchange an OpenID Connect (OIDC) token for a short-lived Google Cloud OAuth 2.0 access token valid for a maximum of 60 minutes.

The external runner assumes the scoped service account identity on the fly, executes its integration tests against the Pub/Sub topic, and finishes without leaving a single static credential at rest.

Configuring Service Account Impersonation for Local Workstations

When freelancers must test publisher or subscriber scripts locally from their developer laptops, use Cloud IAM service account impersonation rather than downloading keyfiles. Under this pattern, the contractor authenticates using their corporate or federated Google identity via the gcloud CLI. You then grant their personal account the Service Account Token Creator role (roles/iam.serviceAccountTokenCreator) solely on the specific, scoped worker service account:

# Grant the contractor permission to impersonate the service account
gcloud iam service-accounts add-iam-policy-binding \
    pubsub-dev-worker@core-platform-prod.iam.gserviceaccount.com \
    --member="user:freelance-developer@external-agency.com" \
    --role="roles/iam.serviceAccountTokenCreator"

The contractor then configures their local environment to automatically generate ephemeral, short-lived tokens during their testing session:

# Contractor runs this on their local workstation
gcloud auth login freelance-developer@external-agency.com

# Configure gcloud to impersonate the worker identity
gcloud config set auth/impersonate_service_account pubsub-dev-worker@core-platform-prod.iam.gserviceaccount.com

# All subsequent pubsub commands use temporary, short-lived credentials
gcloud pubsub topics list

When the contract concludes, revoking the contractor's identity instantly breaks the impersonation link, immediately cutting off access to the underlying service account and Pub/Sub infrastructure.

Operational Playbook for Managing Contractor Access to Google Cloud Pub/Sub Lifecycles

A secure technical architecture must be supported by an operational playbook. Managing third-party developers requires structured lifecycle gates: onboarding, scope modification, and offboarding verification.

Phase 1: Structured Onboarding

  1. Provision an Isolated Sandbox Topic: rarely onboard contractors directly to production event brokers. Create isolated topics with explicit retention limits (e.g., 24 hours) dedicated to development.
  2. Assign Short-Lived Scopes: Configure identity federations or impersonation rights rather than keyfiles. Where IAM policies are bound directly, enforce an IAM Condition with a fixed expiration timestamp.
  3. Attach Message Schemas: Bind Avro or Protobuf schemas to sandbox topics to enforce contract validation prior to code review.

Phase 2: Mid-Project Scope Adjustments

As project deliverables evolve, a freelancer who originally authored an event publisher may be tasked with building a downstream consumer service. Transitioning roles must follow a strict "grant-and-prune" model:

  • Do not escalate a publisher's permissions by adding broader project roles.
  • Create the specific downstream subscription manually.
  • Bind roles/pubsub.subscriber directly to the subscription.
  • If the original publishing deliverable is complete, immediately remove the roles/pubsub.publisher binding from the upstream topic.

Phase 3: Automated Offboarding and Verification

The most dangerous operational oversight is leaving "dangling" subscriptions. When a contractor finishes their work, ops teams often delete the contractor's user account but leave their subscription attached to the topic. Because the subscription is still registered, Pub/Sub continues routing every published message into that subscription's storage backlog. This inflates cloud storage costs and holds onto unacknowledged customer data indefinitely.

Clean teardown requires three sequential steps:

  1. Drain and Delete Subscriptions: Delete the contractor-specific subscription to stop message accumulation.
  2. Revoke Topic and IAM Bindings: Remove the contractor's identity from all resource-level topic and subscription IAM policies.
  3. Read Back Provider State: Programmatically verify that the identity does not retain active permissions on any cloud asset.

Organizations standardizing this lifecycle can deploy dedicated tooling such as a contractor access manager to schedule time-bound grants, streamline the offboarding process, and ensure access rights are completely removed when contracts expire.

Audit Logging, Message Monitoring, and Anomaly Detection

To detect anomalies and verify compliance, engineering teams must maintain continuous visibility over all interactions with the messaging bus.

Enabling Data Access Audit Logs

By default, Google Cloud Cloud Audit Logs capture "Admin Activity" (such as creating topics or deleting subscriptions) for free. However, "Data Access" logs—which record operational calls like Pull, Acknowledge, and Publish—are disabled by default due to high log volume.

When working with external contractors, enable Data Access logs specifically for the Pub/Sub service within your project audit configuration:

# terraform/audit_policy.tf
resource "google_project_iam_audit_config" "pubsub_audit" {
  project = "core-platform-prod"
  service = "pubsub.googleapis.com"

  audit_log_config {
    log_type = "DATA_READ"
  }
  audit_log_config {
    log_type = "DATA_WRITE"
  }
}

This ensures that every pull request executed by an external contractor's identity produces a traceable audit event in Cloud Logging, documenting the exact principal, IP address, and timestamp.

Cloud Monitoring Alerts for Consumer Anomalies

Set up automated Cloud Monitoring alerts to catch misconfigurations or malicious activity early. Two specific metrics should be monitored on any contractor-facing subscription:

  • Unacknowledged Message Count (pubsub.googleapis.com/subscription/num_undelivered_messages): A sudden surge in undelivered messages indicates that the contractor's consumer service is crashing, failing to acknowledge deliveries, or disconnected. Set an alert threshold to trigger an engineering notification if undelivered messages exceed 10,000 for more than 15 minutes.
  • If the oldest unacknowledged message age metric approaches the subscription's message retention duration (defaulting to seven days), unacknowledged messages are at risk of being discarded before processing.

For teams that must retain records for enterprise governance, maintaining structured access audit logs helps security leads reconcile contractor identities against actual cloud provider modifications during internal compliance reviews.

Governance Architecture: Integrating Access Management Tools

While native Google Cloud IAM controls are robust, managing freelance talent across real-world engineering teams requires coordinating access across diverse ecosystems. A freelance engineer building an event consumer rarely works solely within Google Cloud; their day-to-day workflow spans task tracking in Asana, source control in GitHub or GitLab, collaboration in Slack, and infrastructure across multi-cloud environments.

Managing this via manual calendar invites or ad-hoc offboarding tickets inevitably results in forgotten credentials, orphaned cloud subscriptions, and ghost accounts remaining active months after project completion.

To address this complexity, organizations often implement automated coordination systems. Using an auto-revoke tool integration bridges the gap between project management schedules and cloud identity lifecycles. Rather than hoping an engineer remembers to delete a topic binding on a Friday afternoon, teams can establish time-bound access windows upfront that trigger revocation hooks across infrastructure layers automatically.

When evaluating multi-provider identity governance for third-party talent, understand how provider enforcement models operate:

  • Enforced Ecosystems: Tempkey natively enforces access on 10 providers — Slack, Google Workspace, Microsoft 365, GitHub, GitLab, Zoom, AWS IAM, Figma, Dropbox, and Asana. Notion and Trello are limited-native (tracked, not fully enforced) and Zapier/Make are best-effort webhook bridges without automated verification. Slack carries one condition worth stating: automatic deactivation uses Slack's SCIM API, which Slack ships on Business+ and Enterprise only. Below that, Tempkey verifies the removal rather than performing it, so do not promise automatic Slack revocation without naming the plan.
  • Execution and Verification Mechanics: Tempkey executes revocation and reads provider state back to confirm it. Because revocation depends on third-party provider APIs, Tempkey does not guarantee removal within any specific time and surfaces failed or unenforceable revokes in the audit log.
  • Credential Protection: Provider admin tokens are write-only in the browser and encrypted at rest using AWS KMS in production; they are rarely displayed again after submission.
  • Compliance and Logging Frameworks: Tempkey gives you an exportable, append-only audit trail to support your own compliance and offboarding records. Tempkey gives users an exportable audit trail to support compliance records, though Tempkey does not currently hold SOC 2, ISO 27001, HIPAA, or PCI certification. Tempkey keeps an append-only audit trail you can export to CSV or PDF. Describe it as append-only, not immutable, and do not claim unlimited retention. Furthermore, Tempkey's privacy documentation is being finalized.
  • Service Architecture and Integration: Tempkey is a proprietary hosted SaaS product. No source license is published. Tempkey is a hosted cloud service; there is no self-hosted or on-premise deployment option. Sign-in is passwordless — magic links plus WebAuthn/passkeys. Tempkey does not offer SSO/SAML today, nor does it offer customer custom or vanity domains.
  • API Connectivity: For custom internal orchestration, Tempkey has a public REST API covering grants, extension, revocation with read-back verification, integrations, the audit trail, and API-key management. Keys are bearer tokens with read/write scopes; an OpenAPI 3 spec is published at api.tempkey.io/openapi.json and human docs at tempkey.io/docs/api.
  • Commercial Model: Enterprise IT suites (e.g. Rippling, Okta, JumpCloud) bundle contractor offboarding inside larger, per-employee-priced products; their pricing changes often and is frequently quote-gated. Tempkey prices per active contractor grant. Plans are month-to-month (Free / $39 Team / $99 Business) with active-grant limits of 2 / 10 / 30. Business includes extended audit-history retention.

By pairing granular Google Cloud IAM topic constraints with an automated access lifecycle system, engineering leads eliminate persistent security risks while giving freelance developers the exact operational access they need to execute their deliverables.

Frequently Asked Questions

What is the most restrictive IAM role for a contractor who only needs to push messages to a Pub/Sub topic?

The most restrictive role is roles/pubsub.publisher (Pub/Sub Publisher) bound directly to the target topic. This grants only the pubsub.topics.publish permission. A principal with this role cannot inspect topic metadata, list topics, view existing messages, or create subscriptions. rarely grant project-level roles or the roles/pubsub.editor role when an external developer only needs write access to an ingest stream.

How can I prevent a contractor from viewing sensitive production data in Pub/Sub message payloads?

You can prevent contractors from seeing sensitive payloads by using subscription message filtering, payload schema constraints, or dedicated development sandbox topics. Subscription filtering ensures that only messages bearing specific attributes (such as environment = "sandbox") reach the contractor's consumer, with unmatching production messages acknowledged and discarded automatically by the broker. Additionally, schema contracts can be used to validate message formats without exposing live database streams.

Why should I avoid giving contractors downloaded service account JSON keys?

Downloaded service account JSON keys are static, long-lived credentials that cannot be constrained by corporate multi-factor authentication or network perimeters. Once downloaded to an unmanaged contractor laptop, keys risk accidental exposure via public Git repositories, local malware, or shared backup drives. Instead, use short-lived authentication patterns such as Workload Identity Federation for external pipelines or Google Cloud service account impersonation for local CLI debugging.

What happens to unacknowledged messages when a contractor subscription is deleted?

When a Pub/Sub subscription is deleted, all unacknowledged messages stored within that specific subscription buffer are immediately dropped from that subscription. However, the messages remain preserved in the underlying topic (up to the topic's configured retention duration) and will continue to be delivered to any other independent subscriptions attached to that topic. Deleting obsolete contractor subscriptions prevents unnecessary message backlog retention billing and avoids orphaned consumer states.

Explore how Tempkey simplifies external identity lifecycles with scheduled access grants, automatic verification, and exportable audit records for engineering teams.