EthicsPortal is whistleblowing software. For a few months, a reporter could record a voice message in the browser. The server changed the pitch of the voice, deleted the original, and only then showed the recording to the case handler.

This week I deleted the whole feature. This post is the recipe I wish I had at the start: how to record audio in a Rails form, how to process it safely, how to make sure the original is really gone, and what a pitch shift does not protect.

In short:

  • Recording in the browser is easy: MediaRecorder plus a hidden file input. The form uploads it like any other file.
  • The hard part is the server. You must never serve the raw file, never keep it, and never trust ffmpeg with an anonymous upload without limits.
  • “Purge” does not delete a file from versioned buckets or backups. You must erase every version yourself.
  • A fixed pitch shift can be reversed in one step. Speaker recognition can still match the voice. A colleague can still recognise it.
  • Every real fix needs a speech model. EthicsPortal promises that no AI processes reports, so I removed the feature.

1. Record in the browser #

The recorder is a Stimulus controller. It records with MediaRecorder, then puts the result into a normal <input type="file">. No upload endpoint, no direct upload: the audio travels with the form submit.

// voice_recorder_controller.js (trimmed)
async start() {
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
  const chunks = []
  const recorder = new MediaRecorder(stream, this.#recorderOptions())
  recorder.addEventListener('dataavailable', e => { if (e.data.size > 0) chunks.push(e.data) })
  recorder.addEventListener('stop', () => this.#finalize(recorder, chunks), { once: true })
  recorder.start()
}

#finalize(recorder, chunks) {
  const type = (recorder.mimeType || 'audio/webm').split(';')[0]
  const file = new File([new Blob(chunks, { type })], `voice-message.${this.#extensionFor(type)}`, { type })
  const transfer = new DataTransfer()
  transfer.items.add(file)
  this.inputTarget.files = transfer.files // the form now "has" the file
}

#recorderOptions() {
  const candidates = ['audio/webm;codecs=opus', 'audio/webm', 'audio/mp4', 'audio/ogg']
  const supported = candidates.find(type => MediaRecorder.isTypeSupported(type))
  return supported ? { mimeType: supported } : {}
}

Things that bit me:

  • Each browser records a different format. Chrome and Firefox give WebM/Opus. Safari gives MP4/AAC. Pick the first supported type and name the file to match (.webm, .m4a, .ogg).
  • Stop the tracks. If you only stop the recorder, the microphone light stays on. Call stream.getTracks().forEach(t => t.stop()) on stop, on discard and in disconnect().
  • Permission can be refused, and can arrive late. Handle the rejected getUserMedia promise. If the user left the page while the permission prompt was open, stop the stream that arrives after.
  • Cap the length in the browser too. A timer stops the recording at 10 minutes. The server enforces the same limit (see step 4).
  • Preview with an object URL, and revoke it. URL.createObjectURL(blob) for the <audio> preview, URL.revokeObjectURL on discard.
  • Headers. The microphone needs Permissions-Policy: microphone=(self). The preview needs blob: in the CSP media-src. When you remove the feature, set it back to microphone=().
  • Hide the recorder where it cannot work. No MediaRecorder means no recorder. Show a short “write your report instead” message.

2. Accept the upload #

module AnonymizesVoiceRecording
  extend ActiveSupport::Concern

  # Active Storage sniffs the bytes. An audio-only WebM is detected as video/webm,
  # Ogg as application/ogg. Accept the container family; ffmpeg reads the audio anyway.
  CONTENT_TYPES = %w[audio/webm video/webm audio/ogg video/ogg application/ogg
                     audio/mp4 video/mp4 audio/x-m4a audio/mpeg].freeze

  included do
    has_one_attached :voice_recording, service: :encrypted
    validates :voice_recording, content_type: CONTENT_TYPES, size: { less_than_or_equal_to: 25.megabytes }

    before_save { @voice_recording_changed = attachment_changes.key?("voice_recording") }
    after_commit :enqueue_voice_anonymization, on: %i[create update], if: -> { @voice_recording_changed }
  end

  def voice_recording_available?
    voice_recording.attached? && voice_recording.blob.metadata["voice_anonymization_status"] == "done"
  end

  private

  def enqueue_voice_anonymization
    blob = voice_recording.blob
    return if blob.nil? || blob.metadata["voice_anonymization_status"].present?

    blob.update!(metadata: blob.metadata.merge("voice_anonymization_status" => "pending"))
    VoiceAnonymizationJob.perform_later(self)
  end
end

Gotchas:

  • Content type. The validation failed for real recordings until I accepted the video/* and application/ogg variants. Active Storage trusts the bytes, not the browser’s label. Some browsers label uploaded .m4a voice memos as audio/x-m4a.
  • A string is not an upload. Active Storage accepts a signed blob ID in place of a file. A crafted form can send the signed ID of a file that belongs to someone else (every file URL contains one) and attach it to its own record. Keep only real uploads in your params:

    def uploads_only(permitted, *keys)
      keys.each do |key|
        permitted.delete(key) unless permitted[key].is_a?(ActionDispatch::Http::UploadedFile)
      end
      permitted
    end
    
  • Feature flag at the params level. When an organisation has voice switched off, drop the param in the controller. A form that posts a recording anyway gets a report without it.
  • Enqueue in after_commit. If the job runs before the transaction commits, it may not find the record. If the transaction rolls back, the job should never run.

3. Never serve the raw file #

Until the job finishes, the original voice is on disk. Every place that can send it to a browser must refuse it. The view checks voice_recording_available?. That is not enough: a signed blob URL works without your view.

Add a guard to Active Storage’s own serving controllers:

module ActiveStorage::VoiceAnonymizationGuard
  extend ActiveSupport::Concern

  included { before_action :reject_unprocessed_voice_recording }

  private

  def reject_unprocessed_voice_recording
    return if @blob.metadata["voice_anonymization_status"] == "done"

    head :forbidden if @blob.attachments.any? { it.name == "voice_recording" }
  end
end

# config/initializers/active_storage_voice_guard.rb
Rails.application.config.to_prepare do
  [ActiveStorage::Blobs::RedirectController, ActiveStorage::Blobs::ProxyController].each do |controller|
    controller.include(ActiveStorage::VoiceAnonymizationGuard)
  end
end

Include it in every controller that streams blobs. If you serve representations or previews, guard those too: variants and previews are generated and stored before your guard runs, so they can contain the raw data.

Also turn off what Rails runs on uploads by default:

Rails.application.config.after_initialize do
  config = Rails.application.config.active_storage
  config.analyzers -= [ActiveStorage::Analyzer::VideoAnalyzer, ActiveStorage::Analyzer::AudioAnalyzer]
  config.previewers -= [ActiveStorage::Previewer::VideoPreviewer]
end

The default analyzers run ffprobe and the video previewer runs ffmpeg on every anonymous upload, without the limits from step 4. Nothing in my app needed a duration or a video thumbnail.

4. The job: run ffmpeg as if the file is hostile #

The file comes from an anonymous person on the internet. ffmpeg has a large parsing surface. Treat it like any untrusted input:

class VoiceAnonymizationJob < ApplicationJob
  PITCH_FACTOR = 0.82
  SAMPLE_RATE = 44_100
  CONVERSION_TIMEOUT = 120
  INPUT_FORMATS = "matroska,ogg,mov,mp3" # containers only: no playlists, no concat

  def perform(record)
    raw_blob = record.voice_recording.blob
    anonymized = nil

    Dir.mktmpdir do |dir|
      input = File.join(dir, "input")
      output = File.join(dir, "voice-message.mp3")
      raw_blob.open { FileUtils.cp(it.path, input) }
      next unless anonymize(input, output)

      anonymized = File.open(output) do |io|
        ActiveStorage::Blob.create_and_upload!(
          io:, filename: "voice-message.mp3", content_type: "audio/mpeg",
          service_name: raw_blob.service_name,
          metadata: { "voice_anonymization_status" => "done" }
        )
      end
    end

    return mark_failed(record) unless anonymized

    record.voice_recording.attach(anonymized)
    raw_blob.purge
    erase_versions(raw_blob.key)
  end

  private

  def anonymize(input, output)
    pid = Process.spawn(
      "ffmpeg", "-hide_banner", "-loglevel", "error", "-nostdin", "-y",
      "-protocol_whitelist", "file", "-format_whitelist", INPUT_FORMATS,
      "-i", input,
      "-t", "600",               # same 10-minute cap as the browser
      "-map_metadata", "-1",     # drop device and app metadata
      "-af", pitch_filter,
      "-ac", "1", "-ar", SAMPLE_RATE.to_s, "-b:a", "96k",
      output,
      out: File::NULL, err: File::NULL, pgroup: true
    )
    status = Timeout.timeout(CONVERSION_TIMEOUT) { Process.wait2(pid).last }
    pid = nil
    status.success?
  rescue Timeout::Error
    false
  ensure
    if pid
      Process.kill("KILL", -pid) rescue nil # the whole process group
      Process.wait(pid) rescue nil         # reap it, or you collect zombies
    end
  end

  # Lower the pitch, then speed up so the length stays the same.
  # atempo accepts 0.5–2.0; 1 / 0.82 ≈ 1.22 is inside.
  def pitch_filter
    "aresample=#{SAMPLE_RATE},asetrate=#{(SAMPLE_RATE * PITCH_FACTOR).round}," \
      "atempo=#{(1.0 / PITCH_FACTOR).round(4)},aresample=#{SAMPLE_RATE}"
  end
end

What each guard is for:

  • -protocol_whitelist file and -format_whitelist: an HLS playlist or a concat file can make ffmpeg open other local files or URLs. Allow only the containers browsers actually produce.
  • -t: a 25 MB file can still decode to hours of audio. Cap the output length.
  • Timeout + process group kill + reap: a crafted file can make ffmpeg run forever. Timeout alone leaves the process running. Spawn it in its own group, kill the group, then wait so it does not become a zombie.
  • No shell: pass an argument array to Process.spawn, never a string.
  • Fail closed: if ffmpeg is missing, retry a few times. If it still fails, purge the raw file and set voice_recording_failed_at on the record. The blob is gone, so the failure has to live on the record. The handler sees “could not be processed”. Nobody ever hears the original.
  • Health check: an ffmpeg binary missing from the Docker image silently blocks every voice report. Add a check that the binary exists.

5. “Purge” does not mean gone #

blob.purge deletes the object from your storage service. Look at what is left:

  • Versioned buckets keep the previous version for their lifecycle period (28 days for me) after a delete.
  • A mirror or backup bucket may get its copy after your purge, if the mirror job runs late.
  • Encryption keys outlive the file. With per-file SSE-C keys stored in the database, the key is in job arguments (kept for days after the job finishes) and in nightly database dumps. Key plus old version equals the original voice.

So the raw recording needs a real erase: list every version and delete marker of that key in every bucket, and delete them by version ID. Run it twice, once right away and once after the mirror job’s settle time:

def self.erase_versions(key)
  [mirror.primary, *mirror.mirrors].select { it.respond_to?(:bucket) }.each do |service|
    client = service.bucket.client
    listing = client.list_object_versions(bucket: service.bucket.name, prefix: key)

    (listing.versions + listing.delete_markers).select { it.key == key }.each do |version|
      client.delete_object(bucket: service.bucket.name, key:, version_id: version.version_id)
    end
  end
end

# in the job
EraseFileVersionsJob.perform_later(key)
EraseFileVersionsJob.set(wait: 1.hour).perform_later(key)

Note prefix: key returns other keys that start with the same characters. Filter on the exact key before you delete.

6. What a pitch shift does not protect #

This is the part that made me delete the feature.

  • It can be reversed. The shift above multiplies every frequency by 0.82, the same number for every recording. Anyone who knows or guesses the number divides by it. In my test, one inverse pass on a downloaded recording brought back the speaker’s fundamental frequency and almost all of the spectral envelope: the correlation with the original went from 0.53 to 0.97.
  • A random factor per recording stops only that attack. Speaker recognition software still links pitch-, formant- and speed-shifted speech to a known voice. Research from the VoicePrivacy Challenge has shown for years that signal-processing disguises give weak protection once the attacker knows the method.
  • The most likely attacker is a colleague. In a workplace report, the person listening often knows the reporter. Accent, rhythm, habits and choice of words survive any audio filter. So do background sounds.

Under the GDPR, a voice recording is personal data, and it becomes biometric data once it is processed to identify a person. Call a pitch shift a disguise. Never call it anonymisation, in the UI, in the DPIA, or in marketing.

The options I looked at:

Option Removes the voice? Needs a speech model?
Fixed pitch shift (what I built) No, reversible No
Random pitch + formant shift No, software still matches No
Neural voice conversion Partly, still leaks in research Yes
Server speech-to-text, delete the audio Yes Yes, on your servers
Speech-to-text in the browser, delete the audio Yes, audio never leaves the device Yes, shipped or the browser’s own

Every option that really removes the voice needs a speech model. If your product can use one, the best design is the last row: transcribe on the device, let the reporter read and correct the transcript before sending, and never upload audio. Check language support first. In Chrome, on-device recognition (SpeechRecognition with processLocally: true) covered only some EU languages when I tested it, and Safari gives no on-device guarantee.

7. Why I deleted it #

EthicsPortal promises that no AI processes whistleblower reports. That rules out every option that removes the voice. What was left was a disguise I had to keep warning people about, plus ffmpeg in the Docker image, a guard in Active Storage, a version-erase job, a DPIA section and a setting in every channel.

The law did not need it either. The EU Whistleblowing Directive (Art. 9(2)) lets internal channels accept reports in writing, orally, or both. Oral reporting works with a phone number and an in-person meeting on request, and a handler can write down an oral report for the reporter to check.

So the feature is gone. A simple claim replaces it: EthicsPortal does not record the reporter’s voice.

If you build voice intake anyway, the checklist:

  1. Record with MediaRecorder, upload through the form, stop the tracks.
  2. Accept the container family, cap size and length, and keep only real uploads in params.
  3. Mark the blob pending and guard every serving path until it is done. Turn off the default media analyzers and previewers.
  4. Run ffmpeg with protocol and format allowlists, a length cap, no metadata, a timeout and a process-group kill.
  5. Purge the raw file, then erase every version in every bucket, twice.
  6. If processing fails, delete the original and record the failure. Never fall back to the raw file.
  7. Call it what it is. A pitch shift is a disguise.

More on the privacy side, without code: Voice distortion does not keep whistleblowers anonymous.