fix(provider/docker): Ensure auto-assigned container name starts with valid characters (#13678)

* Ensure container name starts with valid characters when name is auto-assigned
This commit is contained in:
Taru Garg 2025-06-03 20:45:26 +05:30 committed by GitHub
parent 73db3ce45e
commit e08fbad643
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 68 additions and 3 deletions

View file

@ -91,9 +91,7 @@ module VagrantPlugins
def create_params
container_name = @provider_config.name
if !container_name
container_name = "#{@env[:root_path].basename.to_s}_#{@machine.name}"
container_name.gsub!(/[^-a-z0-9_]/i, "")
container_name << "_#{Time.now.to_i}"
container_name = generate_container_name
end
image = @env[:create_image]
@ -156,6 +154,15 @@ module VagrantPlugins
result
end
def generate_container_name
container_name = "#{@env[:root_path].basename.to_s}_#{@machine.name}"
# Remove leading -/_ and any non-alphanumeric, non-hyphen/underscore characters
container_name.gsub!(/\A[^a-zA-Z0-9]+|[^-a-z0-9_]/i, "")
container_name << "_#{Time.now.to_i}"
container_name
end
end
end
end

View file

@ -55,4 +55,62 @@ describe VagrantPlugins::DockerProvider::Action::Create do
expect(result).to eq(["8125:8125", "8125:8125/udp"])
end
end
describe "#generate_container_name" do
let(:env) {{root_path: root_path}}
let(:root_path) {Pathname.new("/path/to/root")}
before do
subject.instance_variable_set(:@env, env)
subject.instance_variable_set(:@machine, machine)
end
it "should not remove any characters" do
expect(subject.generate_container_name).to start_with("root")
end
context "when root path starts with underscores" do
let(:root_path) {Pathname.new("/path/to/__root")}
it "should remove underscores" do
expect(subject.generate_container_name).to start_with("root")
end
end
context "when root path starts with dashes" do
let(:root_path) {Pathname.new("/path/to/--root")}
it "should remove dashes" do
expect(subject.generate_container_name).to start_with("root")
end
end
context "when root path starts with combination of invalid starting characters" do
let(:root_path) {Pathname.new("/path/to/_.-_-root")}
it "should remove invalid starting characters" do
expect(subject.generate_container_name).to start_with("root")
end
end
context "when root path ends with underscores" do
let(:root_path) {Pathname.new("/path/to/root__")}
it "should not remove trailing underscroes" do
expect(subject.generate_container_name).to start_with("root_")
end
end
context "when root path ends with invalid characters" do
let(:root_path) {Pathname.new("/path/to/root_.")}
it "should remove invalid trailing characters" do
expect(subject.generate_container_name).to start_with("root_")
end
end
context "when root path contains invalid characters" do
let(:root_path) {Pathname.new("/path/to/root-.path_.")}
it "should only remove invalid characters" do
expect(subject.generate_container_name).to start_with("root-path_")
end
end
end
end